/**
 * 用户信息路由
 * 处理用户个人资料和相关操作的API端点
 */

const express = require('express');
const router = express.Router();
const User = require('../models/user');
const Game = require('../models/game');
const { protect, admin, checkOwnership } = require('../middleware/auth');
const { ErrorResponse } = require('../middleware/error');

/**
 * @desc    获取当前用户信息
 * @route   GET /api/v1/users/me
 * @access  私有
 */
router.get('/me', protect, async (req, res, next) => {
    try {
        const user = await User.findById(req.user._id);
        
        res.status(200).json({
            success: true,
            user
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    更新用户个人资料
 * @route   PUT /api/v1/users/me
 * @access  私有
 */
router.put('/me', protect, async (req, res, next) => {
    try {
        const { username, email, bio, avatar } = req.body;
        
        // 创建更新对象
        const updateData = {};
        if (username) updateData.username = username;
        if (email) updateData.email = email;
        if (bio !== undefined) updateData.bio = bio;
        if (avatar) updateData.avatar = avatar;
        
        // 检查用户名唯一性
        if (username) {
            const existingUser = await User.findOne({ username });
            if (existingUser && existingUser._id.toString() !== req.user._id.toString()) {
                return next(new ErrorResponse('该用户名已被使用', 400));
            }
        }
        
        // 检查邮箱唯一性
        if (email) {
            const existingUser = await User.findOne({ email });
            if (existingUser && existingUser._id.toString() !== req.user._id.toString()) {
                return next(new ErrorResponse('该邮箱已被注册', 400));
            }
        }
        
        // 更新用户信息
        const updatedUser = await User.findByIdAndUpdate(
            req.user._id,
            updateData,
            { new: true, runValidators: true }
        );
        
        res.status(200).json({
            success: true,
            message: '个人资料更新成功',
            user: updatedUser
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    获取用户上传的游戏
 * @route   GET /api/v1/users/me/games
 * @access  私有
 */
router.get('/me/games', protect, async (req, res, next) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const startIndex = (page - 1) * limit;
        
        // 查询用户上传的游戏总数
        const total = await Game.countDocuments({ author: req.user._id });
        
        // 查询用户上传的游戏
        const games = await Game.find({ author: req.user._id })
            .sort({ createdAt: -1 })
            .skip(startIndex)
            .limit(limit);
        
        res.status(200).json({
            success: true,
            count: games.length,
            total,
            page,
            pages: Math.ceil(total / limit),
            games
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    收藏/取消收藏游戏
 * @route   POST /api/v1/users/me/favorites/:id
 * @access  私有
 */
router.post('/me/favorites/:id', protect, async (req, res, next) => {
    try {
        const gameId = req.params.id;
        
        // 检查游戏是否存在
        const game = await Game.findById(gameId);
        if (!game) {
            return next(new ErrorResponse('游戏不存在', 404));
        }
        
        // 获取用户信息
        const user = await User.findById(req.user._id);
        
        // 检查游戏是否已收藏
        const isFavorited = user.favoriteGames.includes(gameId);
        
        if (isFavorited) {
            // 如果已收藏，则取消收藏
            user.favoriteGames = user.favoriteGames.filter(
                id => id.toString() !== gameId
            );
            await user.save();
            
            res.status(200).json({
                success: true,
                message: '已取消收藏',
                isFavorited: false
            });
        } else {
            // 如果未收藏，则添加收藏
            user.favoriteGames.push(gameId);
            await user.save();
            
            res.status(200).json({
                success: true,
                message: '收藏成功',
                isFavorited: true
            });
        }
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    获取收藏的游戏列表
 * @route   GET /api/v1/users/me/favorites
 * @access  私有
 */
router.get('/me/favorites', protect, async (req, res, next) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const startIndex = (page - 1) * limit;
        
        // 获取用户信息并填充收藏游戏
        const user = await User.findById(req.user._id);
        
        // 查询收藏游戏总数
        const total = user.favoriteGames.length;
        
        // 查询分页后的收藏游戏
        const favoriteGameIds = user.favoriteGames.slice(startIndex, startIndex + limit);
        
        // 获取游戏详细信息
        const games = await Game.find({ _id: { $in: favoriteGameIds } })
            .populate('author', 'username avatar');
        
        res.status(200).json({
            success: true,
            count: games.length,
            total,
            page,
            pages: Math.ceil(total / limit),
            games
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    删除用户账号
 * @route   DELETE /api/v1/users/me
 * @access  私有
 */
router.delete('/me', protect, async (req, res, next) => {
    try {
        // 删除用户上传的游戏
        await Game.deleteMany({ author: req.user._id });
        
        // 删除用户账号
        await User.findByIdAndDelete(req.user._id);
        
        res.status(200).json({
            success: true,
            message: '账号已删除'
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    管理员获取所有用户列表
 * @route   GET /api/v1/users
 * @access  私有/管理员
 */
router.get('/', protect, admin, async (req, res, next) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const startIndex = (page - 1) * limit;
        
        // 查询用户总数
        const total = await User.countDocuments();
        
        // 查询用户列表
        const users = await User.find()
            .sort({ createdAt: -1 })
            .skip(startIndex)
            .limit(limit);
        
        res.status(200).json({
            success: true,
            count: users.length,
            total,
            page,
            pages: Math.ceil(total / limit),
            users
        });
    } catch (error) {
        next(error);
    }
});

module.exports = router; 